﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using System.Drawing;
using Silvermoon.Windows.Styles;
using Silvermoon.Windows;
using Silvermoon.Shapes;
using Silvermoon.OpenGL;
using Silvermoon.Images;
using Passwords.Biz;
using Silvermoon.UI;
using Silvermoon.Controls.Buttons;
using Passwords.Utils;
using Silvermoon.Controls.Forms;

namespace Passwords.Pages
{
    public class EditLabelDetailPage : Page
    {
        private Toolbar toolbar;
        private TextBox nameTextBox;
        private Button typeButton;
        private Button indexButton;
        private PasswordLabel label;
        private int displayIndex;
        private ItemType type;

        public EditLabelDetailPage()
            : base()
        {
            InitializePage();
        }

        public PasswordLabel Label
        {
            get { return label; }
            set
            {
                if (label != value)
                {
                    label = value;
                    OnLabelChanged();
                }
            }
        }

        public bool IsSaveEnabled
        {
            get { return toolbar.Buttons[0].Enabled; }
            set
            {
                if (IsSaveEnabled != value)
                {
                    toolbar.Buttons[0].Enabled = value;
                }
            }
        }

        public bool IsDeleteEnabled
        {
            get { return toolbar.Buttons[1].Enabled; }
            set
            {
                if (IsDeleteEnabled != value)
                {
                    toolbar.Buttons[1].Enabled = value;
                }
            }
        }

        private bool focusOnShown = true;

        protected virtual void InitializePage()
        {
            this.Title = "EDIT LABEL";

            Styles = StylePool.Metro;
            int border = 20;
            Style style = ButtonStyles.PickerStyle;
            //Style style = new ButtonStyle { Padding = new Margin(20, 4, null, 4) };
            nameTextBox = new TextBox { Margin = new Margin(border, border + 60, border, null), Height = 64 };
            nameTextBox.Watermark = new StringShape { Text = "Enter label name", Opacity = 160, Color = PhoneColors.Dark };
            nameTextBox.TextChanged += new EventHandler(nameTextBox_TextChanged);

            typeButton = new Button { Margin = new Margin(border, border + 200, border, null), Height = 64, Style = style, Content = "Text", Font = FontCache.MediumRegularFont };
            indexButton = new Button { Margin = new Margin(border, border + 340, border, null), Height = 64, Style = style, Content = "1", Font = FontCache.MediumRegularFont };

            typeButton.Tap += OnTypeTap;
            indexButton.Tap += OnIndexTap;

            Label nameLabel = new Label("Name") { Location = new Point(border, border + 10) };
            Label typeLabel = new Label("Type") { Location = new Point(border, border + 150) };
            Label indexLabel = new Label("Display index") { Location = new Point(border, border + 290) };
            Controls.Add(nameLabel, typeLabel, indexLabel, nameTextBox, typeButton, indexButton);

            toolbar = new Toolbar();
            toolbar.AddButton(SysImages.Ok).Tap += new EventHandler<TapEventArgs>(OnOK);
            toolbar.AddButton(SysImages.RecycleBin).Tap += new EventHandler<TapEventArgs>(OnDeleteLabel);
            toolbar.AddButton(SysImages.Cancel, Page.BackCommand);
            Toolbar = toolbar;
        }

        void nameTextBox_TextChanged(object sender, EventArgs e)
        {
            IsSaveEnabled = !string.IsNullOrEmpty(nameTextBox.Text);
        }

        void OnDeleteLabel(object sender, TapEventArgs e)
        {
            if (label == null) throw new ArgumentNullException("label");
            int n = label.GetAssociatedPasswords();
            string text = n > 0 ? string.Format("Label is being used by {1} password{2}. Delete label anyway?", label.Name, n, n > 1 ? "s" : "") : string.Format("Delete label {0}?", label.Name);
            MessageDialog.Show("Delete label", text, "Delete", "Cancel", () =>
            {
                try
                {
                    label.Delete();
                    GoBack();
                }
                catch (Exception ex)
                {
                    MessageDialog.Show("Error deleting label", ex.Message);
                }
            }, null);
        }

        protected override void OnShown()
        {
            base.OnShown();
            if (focusOnShown && label != null && string.IsNullOrEmpty(label.Name))
            {
                nameTextBox.SetFocus();
                nameTextBox.SelectAll();
            }
        }

        void OnOK(object sender, TapEventArgs e)
        {
            displayIndex = label.DisplayIndex;
            label.Name = nameTextBox.Text;
            label.ValueType = type;
            label.Save();
            GoBack();
        }

        protected override void OnBack(HandledEventArgs e)
        {
            label.DisplayIndex = displayIndex;
            base.OnBack(e);
        }


        private void OnLabelChanged()
        {
            if (label != null)
            {
                type = label.ValueType;
                displayIndex = label.DisplayIndex;
                nameTextBox.Text = label.Name;
                typeButton.Content = type.ToString();
                indexButton.Content = displayIndex.ToString();
                typeButton.Enabled = label.IsNew || (label.GetAssociatedPasswords() == 0);
                IsSaveEnabled = !string.IsNullOrEmpty(label.Name);
                IsDeleteEnabled = !label.IsNew;
            }
        }

        void OnTypeTap(object sender, TapEventArgs e)
        {
            LabelTypePickerPage page = new LabelTypePickerPage { Label = this.label };
            this.NavigateTo(page);
        }

        void OnIndexTap(object sender, TapEventArgs e)
        {
            Page page = new LabelIndexPicker { Label = this.label };
            this.NavigateTo(page);
        }

        private class Bag
        {
            public string name;
            public PasswordLabel label;
            public int displayIndex;
        }

        public override object OnSaveViewState()
        {
            return new Bag { label = this.label, displayIndex = this.displayIndex, name = nameTextBox.Text };
        }

        public override void OnLoadViewState(object viewState)
        {
            Bag bag = viewState as Bag;
            if (bag != null)
            {
                Label = bag.label;
                displayIndex = bag.displayIndex;
                nameTextBox.Text = bag.name;
                focusOnShown = false;
            }
        }

    }
}
